<template>
  <div class="assistant-manage">
    <div class="header">
      <div class="search">
        <span>教师信息：</span>
        <el-input
          v-model="chooseTeacher"
          placeholder="请输入教师姓名"
          size="large"
          style="width: 240px"
        >
        </el-input>
        <el-button class="search-btn" @click="searchFn()">搜索</el-button>
      </div>
      <div class="btns">
        <el-button @click="addAssistant()">添加</el-button>
        <el-button @click="batchDelete()">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="chapter-list">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="教师姓名" width="150" />
        <el-table-column property="userNumber" label="工号" width="200" />
        <el-table-column label="性别" width="150">
          <template #default="scope">
            <span>{{ scope.row.sex == 1 ? "男" : "女" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          property="telephoneNumber"
          label="联系方式"
          width="250"
        />
        <el-table-column property="email" label="邮箱" width="250" />
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button
              size="small"
              text
              type="primary"
              @click="resetPassword(scope.$index, scope.row)"
              style="color: #457aff; font-size: 14px"
            >
              初始密码
            </el-button>
            <el-button
              size="small"
              text
              type="primary"
              @click="cancelTeaching(scope.$index, scope.row)"
              style="color: #457aff; font-size: 14px"
            >
              解除授课
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加/编辑助教弹窗 -->
    <el-dialog
      class="add-dialog"
      :close-on-click-modal="false"
      v-model="addDialogVisiable"
      width="730px"
      @close="closeAddDialog()"
      center
    >
      <div class="dialog-body">
        <el-form
          ref="addform"
          :inline="true"
          :model="addform"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="工号 :" prop="userNumber">
            <el-input
              v-model="addform.userNumber"
              placeholder="请输入工号"
              @input="debouncedCheckUserNumber"
            ></el-input>
          </el-form-item>
          <el-form-item label="教师姓名 :" prop="name">
            <el-input
              v-model="addform.name"
              maxlength="10"
              placeholder="请输入教师姓名"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系方式 :" prop="telephoneNumber">
            <el-input
              v-model="addform.telephoneNumber"
              maxlength="11"
              placeholder="请输入联系方式"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱 :" prop="email">
            <el-input
              v-model="addform.email"
              maxlength="50"
              placeholder="请输入邮箱"
              :disabled="checkDisabled"
            ></el-input>
          </el-form-item>
          <el-form-item label="性别 :" prop="sex" style="width: 100%">
            <el-radio-group
              v-model="addform.sex"
              placeholder="请选择性别"
              :disabled="checkDisabled"
            >
              <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" color="#457aff" @click="saveAdd()"
          >保 存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from "lodash";
export default {
  data() {
    return {
      courseId: "",
      chooseTeacher: "",
      currentPage: 1,
      pageSize: 10,
      tableData: [],
      addDialogVisiable: false,
      addform: {
        email: "",
        name: "",
        userNumber: "",
        telephoneNumber: "",
        sex: 1,
      },
      rules: {
        name: [{ required: true, message: "请输入教师姓名", trigger: "blur" }],
        userNumber: [
          { required: true, message: "请输入工号", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
      },
      totalCount: 0,
      multipleSelection: [],
      checkDisabled: false,
      debouncedCheckUserNumber: null,
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getAssistantList();
    this.debouncedCheckUserNumber = debounce(this.checkUserNumber, 500);
  },
  methods: {
    // 搜索
    searchFn() {
      this.currentPage = 1;
      this.getAssistantList();
    },

    // 获取助教列表
    getAssistantList() {
      this.$axios
        .get(
          `/tes/user/OtherTeacherPage?pageNum=${this.currentPage}&pageSize=${this.pageSize}&userInfo=${this.chooseTeacher}&courseId=${this.courseId}`
        )
        .then((res) => {
          this.tableData = res.data.content;
          this.totalCount = res.data.total;
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getAssistantList();
    },
    addAssistant() {
      this.addDialogVisiable = true;
      this.checkDisabled = false;
    },
    // 保存添加助教
    saveAdd() {
      this.$axios
        .post(
          `/tes/user/createAssistant?identity=1&courseId=${this.courseId}`,
          this.addform
        )
        .then((res) => {
          this.getAssistantList();
          this.addDialogVisiable = false;
          this.checkDisabled = false;
        });
    },

    closeAddDialog() {
      this.addDialogVisiable = false;
      this.$refs.addform.resetFields();
    },
    // 初始密码
    resetPassword(index, row) {
      this.$axios.put(`/tes/user/${row.id}/init-password`).then((res) => {
        this.$message.success("初始化成功");
      });
    },

    // 解除授课
    cancelTeaching(index, row) {
      this.$axios
        .put(
          `/tes/user/RelievingTeaching?userId=${row.id}&courseId=${this.courseId}`
        )
        .then((res) => {
          this.$message.success("解除授课成功");
          this.getAssistantList();
        });
    },

    // 批量删除
    batchDelete() {
      this.$confirm("确定要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .post(
            `/tes/user/batch-delete?courseId=${this.courseId}&errorFlag=true`,
            this.multipleSelection
          )
          .then((res) => {
            this.$message.success("批量删除成功");
            this.getAssistantList();
            // 如果当前页没有数据了，回到上一页
            const maxPage = Math.ceil(this.total / this.pageSize);
            if (this.currentPage > maxPage && maxPage > 0) {
              this.currentPage = maxPage;
            }
          });
      });
    },

    // 检查学号是否存在
    checkUserNumber() {
      this.$axios
        .post(`/tes/user/student/info?identity=1`, {
          userNumber: this.addform.userNumber,
        })
        .then((res) => {
          if (res.code == "200") {
            if (res.data) {
              this.addform.name = res.data.name;
              this.addform.telephoneNumber = res.data.telephoneNumber;
              this.addform.email = res.data.email;
              if (typeof res.data.sex == undefined) {
                this.addform.sex = 1;
              } else {
                this.addform.sex = res.data.sex;
              }
              this.$message({
                message: "自动填充已存在的教师",
                type: "warning",
              });
              this.checkDisabled = true;
            } else {
              this.addform.telephoneNumber = "";
              this.addform.email = "";
              this.addform.name = "";
              this.checkDisabled = false;
            }
          } else {
            this.$message.error(res.message);
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.assistant-manage {
  background-color: #fff;
  padding: 10px 40px 40px 80px;
  box-sizing: border-box;
  min-height: 550px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        font-size: 16px;
        color: #252e54;
      }
      .search-btn {
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #a5beff;
        color: #457aff;
        line-height: 40px;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .el-button {
        background: #457aff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
  .chapter-list {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;
    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
  }

  .dialog-body {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    .el-button {
      color: #457aff;
      border: 1px solid #457aff;
      margin-right: 10px;
      &:hover {
        background-color: #457aff;
        color: #fff;
      }
    }
  }
}
</style>